package com.dr.cmdb.core.filedcheck;

import com.dr.cmdb.core.dto.FiledCheckDto;
import com.google.common.collect.Lists;
import org.springframework.beans.BeansException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @ProjectName: cmdb
 * @Package: com.dr.cmdb.application.filedcheck
 * @Description: java类作用描述
 * @Author: duanrui
 * @CreateDate: 2021/3/30 10:10
 * @Version: 1.0
 * <p>
 * Copyright: Copyright (c) 2021
 */
@Component
public class FiledCheckHandlerFactory implements CommandLineRunner, ApplicationContextAware {
    private volatile ApplicationContext applicationContext;


    private static AbstractFiledCheckHandler handlers;


    /**
     * 拼接变种责任链
     *
     * @param args
     */
    @Override
    public void run(String... args) {
        Collection<AbstractFiledCheckHandler> checkHandlers = this.applicationContext.getBeansOfType(AbstractFiledCheckHandler.class).values();
        List<AbstractFiledCheckHandler> list = Lists.newArrayList(checkHandlers);
        Collections.sort(list, AnnotationAwareOrderComparator.INSTANCE);
        for (int i = 0; i < list.size() - 1; i++) {
            list.get(i).setNextHandler(list.get(i + 1));
        }
        handlers = list.get(0);
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 执行方法校验
     *
     * @param filedCheckDto
     */
    public static void processHandler(FiledCheckDto filedCheckDto) {
        handlers.handler(filedCheckDto);
    }


}
